'''
Модуль получения различной информации о пользователях

@author: DC Osanve <dcosanve@gmail.com>

@license: GNU GPLv3
'''

import json
from urllib import request

from twitter import globl


def get_user_info(account, mode=globl.ALL):
    ''' Функция возвращает информацию о пользователе.

        На входе: account (mode)?
                        account - логин пользователя
                        mode - список плей для получения информации

        На выходе: (data|result|1|2)
                        data - все данные о пользователе
                        result - выбранные данные о пользователе
                        1 - неверный параметр mode
                        2 - не выбран ни один из параметров
                        3 - неверный параметр account
    '''
    q_url = 'https://api.twitter.com/1/users/show.json?'
    if(type(account) == str):
        q_url += 'screen_name=' + account
    elif(type(account) == int):
        q_url += 'user_id=' + str(account)
    else:
        return 3
    req = request.Request(q_url)
    opener = request.build_opener()
    f = opener.open(req)
    data = f.read()
    data = json.loads(data.decode())

    if(mode == globl.ALL):
        return data
    else:
        if((type(mode) == list) and (len(mode) != 0)):
            result = {}
            for i in mode:
                try:
                    result[i] = data[i]
                except KeyError:
                    return 1
            return result
        else:
            return 2

def get_followers(account):
    q_url = 'https://api.twitter.com/1/followers/ids.json?'
    if(type(account) == str):
        q_url += 'screen_name=' + account
    elif(type(account) == int):
        q_url += 'user_id=' + str(account)
    else:
        return 3

    ids = []
    cursor = -1
    while(cursor != 0):
        url = q_url + '&cursor=' + str(cursor)
        req = request.Request(url)
        opener = request.build_opener()
        f = opener.open(req)
        data = f.read()
        data = json.loads(data.decode())
        ids += data['ids'][:]
        cursor = data['next_cursor']

    return ids

def get_friends(account):
    q_url = 'https://api.twitter.com/1/friends/ids.json?'
    if(type(account) == str):
        q_url += 'screen_name=' + account
    elif(type(account) == int):
        q_url += 'user_id=' + str(account)
    else:
        return 3

    ids = []
    cursor = -1
    while(cursor != 0):
        url = q_url + '&cursor=' + str(cursor)
        req = request.Request(url)
        opener = request.build_opener()
        f = opener.open(req)
        data = f.read()
        data = json.loads(data.decode())
        ids += data['ids'][:]
        cursor = data['next_cursor']

    return ids

def get_no_followback(account):
    friends = get_friends(account)
    followers = get_followers(account)
    
    no_followback = []
    for i in friends:
        if(i not in followers):
            no_followback.append(i)

    return no_followback
